package com.beidouapp.security.mvc.interceptor;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONException;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.beidouapp.cache.impl.RedisDefaultAppCacheHelper;
import com.beidouapp.security.model.ReturnDataInfo;
import com.beidouapp.security.model.SessionUser;
import com.beidouapp.security.utils.DscpCommUtils;
import com.beidouapp.utils.UIUtils;

public class SessionInterceptor extends HandlerInterceptorAdapter {
	private final Logger logger = Logger.getLogger(SessionInterceptor.class);

	private String[] allowUrls;
	private String[] tokenUrls;

	@Autowired
	private RedisDefaultAppCacheHelper cacheHelper;

	@SuppressWarnings("unchecked")
	@Override
	public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
		String requestUrl = request.getRequestURI().replace(request.getContextPath(), "");
		if (!requestUrl.startsWith("/api"))
			return true;
		if (null != allowUrls ) {
			for (String url : allowUrls) {
				if (requestUrl.contains(url)) {
					return true;
				}
			}
		}
		HttpSession session = request.getSession(false);
		if (session == null) {
			flush2Response(request, response);
			return false;
		}
		SessionUser user = DscpCommUtils.getSessionUser(session);
		if (user == null) {
			flush2Response(request, response);
			return false;
		} else {
			UIUtils.setSessionUser(user);
		}
		return true;
	}

	protected void flush2Response(HttpServletRequest request,
			HttpServletResponse response) throws IOException, JSONException {
		if (request.getContentType() != null
				&& request.getContentType().indexOf("json") != -1) {
			ReturnDataInfo<String> info = new ReturnDataInfo<String>();
			info.setMessage("会话过期，请重新登录!");
			info.setStatusCode(503);
			response.setContentType("application/json;charset=UTF-8");
			JSONObject root = JSONObject.fromObject(info);
			PrintWriter writer = response.getWriter();
			writer.print(root);
			writer.flush();
		} else {
			response.sendRedirect(request.getContextPath() + "/api/tologin");
		}
	}
	
	protected void flushTokenFail2Response(HttpServletRequest request,
			HttpServletResponse response) throws IOException{
		if (request.getContentType() != null
				&& request.getContentType().indexOf("json") != -1) {
			ReturnDataInfo<String> info = new ReturnDataInfo<String>();
			info.setMessage("Token失效，请重新登录!");
			info.setStatusCode(503);
			JSONObject root = JSONObject.fromObject(info);
			response.setContentType("application/json;charset=UTF-8");
			PrintWriter writer = response.getWriter();
			writer.print(root);
			writer.flush();
		} else {
			response.sendRedirect(request.getContextPath() + "/api/special/login");
		}
	}

	protected SessionUser getUserInfoByToken1(String token) {
		SessionUser user = new SessionUser();
		user.setLoginname(token);
		user.setUserName(token);
		return user;
	}

	public void setAllowUrls(String[] allowUrls) {
		this.allowUrls = allowUrls;
	}

	public void setTokenUrls(String[] tokenUrls) {
		this.tokenUrls = tokenUrls;
	}
}
